// utils/timeFormatter.js
function formatTime(time) {
  let date;

  if (typeof time === "number") {
    // 如果是数字，判断是秒还是毫秒
    date = time > 1e12 ? new Date(time) : new Date(time * 1000);
  } else if (typeof time === "string") {
    // 字符串 -> 替换 - 为 / 以兼容 iOS
    date = new Date(time.replace(/-/g, "/"));
    if (isNaN(date.getTime())) {
      // 如果解析失败，尝试按时间戳数字处理
      const ts = parseInt(time);
      if (!isNaN(ts)) {
        date = ts > 1e12 ? new Date(ts) : new Date(ts * 1000);
      } else {
        return ""; // 无法解析
      }
    }
  } else {
    return "";
  }

  const now = new Date();
  const diff = now.getTime() - date.getTime();

  const minute = 60 * 1000;
  const hour = 60 * minute;
  const day = 24 * hour;

  if (diff < minute) {
    return "刚刚";
  } else if (diff < hour) {
    return Math.floor(diff / minute) + "分钟前";
  } else if (diff < day) {
    return Math.floor(diff / hour) + "小时前";
  } else if (diff < 7 * day) {
    const weekDays = ["周日","周一","周二","周三","周四","周五","周六"];
    return weekDays[date.getDay()];
  } else {
    const nowYear = now.getFullYear();
    const year = date.getFullYear();
    if (year === nowYear) {
      return `${(date.getMonth()+1).toString().padStart(2,"0")}-${date.getDate().toString().padStart(2,"0")}`;
    } else {
      return `${year}-${(date.getMonth()+1).toString().padStart(2,"0")}-${date.getDate().toString().padStart(2,"0")}`;
    }
  }
}

module.exports = {
  formatTime
}
